<template>
  <el-dialog
    v-model="centerDialogVisible"
    title="提示"
    width="500"
    align-center
    :before-close="reset"
  >
    <span>{{ props.type.tips }}</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="reset">取消</el-button>
        <el-button type="primary" @click="confirm"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import request from '@/util/request'
import { ref } from 'vue'
import { ElNotification } from 'element-plus'

const props = defineProps({
  type: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['notice-remove'])
const centerDialogVisible = ref(false)
const noticeIds = ref([])
const confirm = () => {
  let ids = []
  ids = noticeIds.value

  console.log(ids)

  if (props.type.type === 0) {
    remove(ids)
  } else if (props.type.type === 1) {
    close(ids)
  }
}

const remove = (ids) => {
  request
    .post('/admin/notice/remove', ids)
    .then((res) => {
      ElNotification.success('删除成功')
      reset()
      emit('notice-remove')
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const close = (ids) => {
  request
    .post('/admin/notice/close', ids)
    .then((res) => {
      ElNotification.success('已关闭')
      reset()
      emit('notice-remove')
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const open = (ids) => {
  centerDialogVisible.value = true
  noticeIds.value = ids
  console.log('接收了', ids, typeof ids, noticeIds.value)
}

const reset = () => {
  centerDialogVisible.value = false
  noticeIds.value = []
}

defineExpose({
  open
})
</script>
